import React, { useState, useEffect } from 'react';
import { Modal, Alert, Input, Button, message, Tooltip } from 'antd';
import userService from '@/api/services/userService';
import { SvgIcon } from '@/components/icon';
import { CopyOutlined, DeliveredProcedureOutlined } from '@ant-design/icons';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import dayjs from 'dayjs';
import { QRCodeSVG } from 'qrcode.react';

import {
  useConfigActions,
  useInitializeData
} from '@/store/configStore';
import { LicenseEditionNameEnum } from '@/common';

interface LicenseModalProps {
  visible: boolean;
  onCancel: () => void;
}

const LicenseModal: React.FC<LicenseModalProps> = ({
  visible,
  onCancel,
}) => {
  const { fetchInitialInfo } = useConfigActions();
  const initializeData = useInitializeData();

  const [licenseInfo, setLicenseInfo] = useState({
    machine_sum: '',
    audience: '',
    not_after: '',
    license: '',
    edition: '',
    invalid_reason: ''
  });

  const [licenseContent, setLicenseContent] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [licenseUrl, setLicenseUrl] = useState("");

  const [isDragging, setIsDragging] = useState(false);

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDragIn = (e) => {
    handleDrag(e);
    setIsDragging(true);
  };

  const handleDragOut = (e) => {
    handleDrag(e);
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    handleDrag(e);
    setIsDragging(false);

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      if (file.type === "text/plain" || file.name.endsWith('.license')) {
        const reader = new FileReader();
        reader.onload = (event) => {
          setLicenseContent(event.target.result);
        };
        reader.readAsText(file);
      } else {
        message.info("该文件不支持解析")
      }
    }
  };

  const fetchLicenseUrl = async () => {
    try {
      userService.fetchLicenseUrl().then(res => {
        setLicenseUrl(res || "")
      });
    } catch (error) {
    }
  };


  const fetchLicense = async () => {
    try {
      const license = await userService.fetchLicense();
      return license;
    } catch (error) {
      console.error('Failed to fetch license:', error);
      throw error;
    }
  };

  const updateLicense = async (licenseData: any) => {
    try {
      const license = await userService.updateLicense(licenseData);
      return license;
    } catch (error) {
      console.error('Failed to update license:', error);
      throw error;
    }
  };

  useEffect(() => {
    if (visible) {
      fetchLicenseInfo();
      fetchLicenseUrl()
    }
  }, [visible]);

  const fetchLicenseInfo = async () => {
    try {
      const response = await fetchLicense();
      setLicenseInfo(response);
      setLicenseContent(response.license);
    } catch (error) {
      console.error('Failed to fetch license info:', error);
    }
  };

  const handleUpdateLicense = async () => {
    try {
      if (!licenseContent) {
        message.error('许可证内容不能为空')
        return
      }
      const licenseData = {
        license_content: licenseContent,
      };
      await updateLicense(licenseData);
      fetchLicenseInfo();
      fetchInitialInfo();
      setIsEditing(false);
      message?.success("License 更新成功")
    } catch (error) {
      console.error('Failed to update license:', error);
    }
  };

  const handleCopyMachineSum = () => {
    if (licenseInfo.machine_sum) {
      message.success('设备指纹已复制到剪贴板');
    } else {
      message.error('设备指纹为空')
    }
  };

  const handleReactivate = () => {
    setIsEditing(true);
    setLicenseContent(''); // 清空许可证内容
  };

  return (
    <Modal
      title={
        <div className="flex items-center">
          <SvgIcon
            icon="home-license"
            size={30}
            style={{
              padding: '3px',
              color: '#6640FF',
            }}
          />
          <span>应用激活</span>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={700}
    >
      <div className="space-y-6">
        <div className="space-y-4">
          <Alert
            message={
              <div className="flex items-center">
                设备指纹：设备唯一标识，用于生成唯一许可证
              </div>
            }
            showIcon
          />
          <div className="flex items-center">
            <span className="w-20 text-gray-600">设备指纹：</span>
            <span className="flex-1 overflow-hidden whitespace-nowrap text-ellipsis">
              {licenseInfo.machine_sum}
            </span>
            <CopyToClipboard text={licenseInfo.machine_sum} onCopy={handleCopyMachineSum}>
              <Tooltip title={"复制设备指纹"}>
                <Button
                  icon={<CopyOutlined />}
                  type="text"
                />
              </Tooltip>
            </CopyToClipboard>
            {
              licenseUrl &&
              <Tooltip title={"获取许可证"}>
                <DeliveredProcedureOutlined onClick={() => { window.open(licenseUrl, '_blank'); }} />
              </Tooltip>
            }
          </div>

          <div className="mt-4">
            {/* <span className="text-gray-600">设备指纹：</span> */}
            <div className="mt-2 flex items-center justify-center">
              {licenseUrl ? <QRCodeSVG value={licenseUrl} size={128} /> : <QRCodeSVG value={licenseInfo.machine_sum} size={128} />}
            </div>
          </div>

          {!isEditing && licenseInfo.audience && (
            <div className="flex items-center">
              <span className="w-20 text-gray-600">授权主体：</span>
              <span>{licenseInfo.audience}</span>
            </div>
          )}

          {!isEditing && licenseInfo?.edition && LicenseEditionNameEnum?.[licenseInfo.edition] && (
            <div className="flex items-center">
              <span className="w-20 text-gray-600">应用版本：</span>
              <span>{LicenseEditionNameEnum?.[licenseInfo.edition]}</span>
            </div>
          )}

          {!isEditing && licenseInfo.not_after && (
            <div className="flex items-center">
              <span className="w-20 text-gray-600">到期时间：</span>
              <span className={`${!initializeData?.is_license_valid
                ? 'text-orange'
                : 'text-black'
                }`}>{dayjs.unix(parseInt(licenseInfo.not_after)).format('YYYY-MM-DD HH:mm:ss')}</span>
            </div>
          )}

          {!isEditing && !initializeData?.is_license_valid && licenseInfo?.invalid_reason && (
            <div className="flex items-center">
              <span className="w-20 text-gray-600">失效原因：</span>
              <span className={`text-orange`}>{licenseInfo?.invalid_reason}</span>
            </div>
          )}

          {!(licenseInfo.audience && !isEditing) && (
            <div className="space-y-2">
              <div className="flex items-center">
                <span className="w-20 text-gray-600">许可证：</span>
              </div>
              <div
                className={`relative border-2 border-dashed rounded-lg p-4 ${isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
                  }`}
                onDragEnter={handleDragIn}
                onDragLeave={handleDragOut}
                onDragOver={handleDragIn}
                onDrop={handleDrop}
              >
                <Input.TextArea
                  placeholder="请输入许可证内容或拖动文件到此区域"
                  rows={10}
                  // allowClear
                  className="w-full bg-transparent"
                  value={licenseContent}
                  onChange={(e) => setLicenseContent(e.target.value)}
                />
              </div>
              {/* <Input.TextArea
                placeholder="请输入许可证内容"
                rows={10}
                className="w-full"
                value={licenseContent}
                onChange={(e) => setLicenseContent(e.target.value)}
              /> */}
            </div>
          )}

          <div>
            {isEditing && (
              <Button
                className="!rounded-button whitespace-nowrap mr-2"
                onClick={() => setIsEditing(false)}
              >
                取消
              </Button>
            )}

            <Button
              type="primary"
              className="!rounded-button whitespace-nowrap"
              onClick={licenseInfo.audience && !isEditing ? handleReactivate : handleUpdateLicense}
            >
              {licenseInfo.audience && !isEditing ? '重新激活' : '激活'}
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default LicenseModal;